var testcaseBizType = require('../models/testcaseBizType.js').bizKeyTypes;

var insertBizKeyType = function (req,res,error) {
    let originalBizKeyList = req.body.params;
    var promise = new Promise(( resolve, reject) => {
        testcaseBizType.find(function(err,result){
            if(err){
                res.send({status:'400',reason:'getAllBizTypeError : '+err});
                reject({status:'400',reason:'getAllBizTypeError : '+err});
            } else {
                let params ={allBizKeyTypeList:result,originalBizKeyList:originalBizKeyList,res:res};
                resolve(params);
            }
        });
    });
    promise.then(getTargetBizKeyTypeList).then(insertTargetBizKeyTypeList);

};

var getTargetBizKeyTypeList = function (params) {

    let targetBizKeyType = [];
    let originalBizKeyList = params.originalBizKeyList;
    let allBizKeyTypeList = params.allBizKeyTypeList;
    let bizKeyType = {};
    originalBizKeyList.forEach(item => {
        bizKeyType = {_id: item.bizKeyType,type : item.bizKeyType};
        if (JSON.stringify(allBizKeyTypeList).toLowerCase().indexOf(JSON.stringify(bizKeyType).toLowerCase()) === -1) {
            targetBizKeyType.push({
                _id: item.bizKeyType,
                type: item.bizKeyType
            });
        }
    });
    let nextParams = {targetBizKeyType: targetBizKeyType, res: params.res};
    return nextParams;
};

var insertTargetBizKeyTypeList = function(nextParams){
    if(nextParams.targetBizKeyType.length > 0){
        let bizKeyTypeSave = new testcaseBizType();
        bizKeyTypeSave.collection.insert(nextParams.targetBizKeyType,function(err,docs){
            if(err){
                nextParams.res.send({status:'400',reason:err});
            } else {
                nextParams.res.send({status:'200',data:docs});
            }
        })
    } else {
        nextParams.res.send({status:'200',data:"not new bizKeyType"})
    }
};


var getAllBizTypes = function (req,res,error) {
    testcaseBizType.find(function(err,result){
        if(err){
            res.send({status:"400",reason:err});
        } else {
            res.send({status:"200", data:result});
        }
    });
};

module.exports = {
    insertBizKeyType: insertBizKeyType,
    getAllBizTypes: getAllBizTypes,

}
